<template>
  <div class="app-container">
    <el-form ref="searchformRef" v-show="showSearch" :inline="true" :model="queryParams" class="demo-form-inline">
      <el-form-item label="名称：" prop="Keywords">
        <el-input v-model="queryParams.Keywords" clearable placeholder="发票号码" />
      </el-form-item>
      <el-form-item label="开票日期：" prop="InvoiceDate">
        <el-date-picker v-model="queryParams.DateRange" type="daterange" range-separator="/" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="YYYY-MM-DD" size="default" />
      </el-form-item>

      <el-form-item label="核验日期：" prop="CheckTime">
        <el-date-picker v-model="queryParams.Filter.CheckTimeRange" type="daterange" range-separator="/"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" size="default" />
      </el-form-item>
      <el-form-item label="核验状态" prop="Status">
        <el-select v-model="queryParams.Status" placeholder="核验状态" size="small" style="width: 240px">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="发票类型" prop="Kind">
        <el-select v-model="queryParams.Filter.InvoiceKind" placeholder="发票类型" size="small" style="width: 240px">
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="销方名称" prop="SalerName">
        <el-input v-model="queryParams.Filter.SalerName" clearable placeholder="名称或税号" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch()">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-button-group>
        <el-button type="default" icon="FullScreen" @click="openScanInvoice()">扫码核验</el-button>
        <el-button type="default" icon="refresh" @click="loadTableData()">刷新</el-button>
        <el-button type="danger" icon="SoldOut" @click="exportData()">导出</el-button>
      </el-button-group>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="loadTableData"></right-toolbar>
    </el-row>
    <el-table ref="gridtable" v-loading="tableloading" :data="tableData" stripe highlight-current-row
      style="width: 100%" :default-sort="{ prop: 'Id', order: 'ascending' }" :summary-method="getSummaries" show-summary
      @sort-change="handleSortChange">
      <el-table-column type="selection" width="50" />

      <el-table-column prop="InvoiceKind" label="发票类型" sortable="custom" width="80" />
      <el-table-column prop="InvoiceNo" label="发票号" sortable="custom" width="220" />
      <el-table-column prop="CheckStatus" label="核对状态" sortable="custom" width="120" />
      <el-table-column prop="CheckName" label="核对人" sortable="custom" width="120" />
      <el-table-column label="核对时间" width="220">
        <template #default="scope">
          <div>
            <span>{{ formatDate(scope.row.CheckTime) }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="Money" label="发票金额" sortable="custom" width="120" />
      <el-table-column label="发票日期" width="220">
        <template #default="scope">
          <div>
            <span>{{ formatDate(scope.row.InvoiceDate) }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="BuyerCode" label="购方税号" sortable="custom" width="220" />
      <el-table-column prop="BuyerName" label="购方名称" sortable="custom" width="180" />

      <el-table-column prop="SalerCode" label="销方税号" sortable="custom" width="220" />
      <el-table-column prop="SalerName" label="销方名称" sortable="custom" width="220" />

      <el-table-column label="pdf" width="80">
        <template #default="scope">
          <div>
            <a :href="scope.row.InvoicePdf" target="_blank">查看</a>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Pagination v-show="queryParams.pageTotal > 0" :total="queryParams.pageTotal"
      v-model:page="queryParams.CurrenetPageIndex" v-model:limit="queryParams.PageSize" @pagination="loadTableData" />
    <el-dialog v-model="dialogFormVisible" width="800" draggable>
      <template #header>
        <el-row style="height: 50px; line-height: 50px;">
          <el-col :span="4">
            <h1>扫码核验</h1>
          </el-col>
          <el-col :span="20">
            <div @click="openManual">手动输入</div>
          </el-col>
        </el-row>

      </template>

      <div>
        <el-row>
          <el-col :span="4" style="font-size: 28px; font-weight: bold">扫码：</el-col>
          <el-col :span="18">
            <el-input ref="inputInvoice" v-model="form.invoice" @keyup.enter="scanInvoice()" />
          </el-col>
        </el-row>
      </div>
      <el-card style="max-width: 780px; font-size: 20px; margin-top: 20px">
        <template #header>
          <div class="card-header">
            <span style="font-size: 21px; font-weight: bold">核验详情</span>
          </div>
        </template>
        <div style="line-height: 60px">
          <div>发票号：{{ form.invoiceNo }}</div>
          <div>金额：{{ form.money }}</div>
          <div>发票日期：{{ form.invoiceDate }}</div>
          <div :style="{ color: form.invoiceColor }">
            核验结果:{{ form.invoiceResult }}
          </div>
        </div>
      </el-card>
    </el-dialog>

    <el-dialog v-model="manualVisible" title="手动输入发票信息" width="800px">
      <el-card>
        <el-autocomplete v-model="checkInvoice" :fetch-suggestions="querySearchAsync" placeholder="请输入发票信息"
          class="full-width-auto" @select="handleSelectInvoice" />
      </el-card>
    </el-dialog>
  </div>
</template>

<script setup name="scanCheck">
import {
  getTHInvoiceListWithPager,
  scanInvoiceInfo,
  exportInvoices,
  getTHInvoiceList
} from "@/api/security/thinvoiceservice";
import defaultSettings from "@/settings";
import { nextTick } from "vue";

const { proxy } = getCurrentInstance();
const tableData = ref([]);
const summary = ref("");
const tableloading = ref(true);
const showSearch = ref(true);
const single = ref(true);
const multiple = ref(true);
const dialogFormVisible = ref(false);
const manualVisible = ref(false);
const checkInvoice = ref("");
const invoiceList = ref([]);
const inputInvoice = ref(null);

const statusOptions = [
  {
    value: "",
    label: "全部",
  },
  {
    value: "已核",
    label: "已核",
  },
  {
    value: "未核",
    label: "未核",
  },
];

const typeOptions = [
  {
    value: "",
    label: "全部",
  },
  {
    value: "1",
    label: "蓝票",
  },
  {
    value: "-1",
    label: "红票",
  },
];

const formLabelWidth = ref("100px");
const currentId = ref(""); // 当前操作对象的ID值，主要用于修改
const ids = ref([]);

const data = reactive({
  queryParams: {
    CurrenetPageIndex: 1,
    PageSize: 20,
    pageTotal: 0,
    Order: "asc",
    Sort: "InvoiceDate",
    Keywords: "",
    DateRange: [],
    Status: "",
    Filter: {
      SalerName: "",
      CheckTimeRange: [],
      InvoiceKind: "",
    },
  },
  form: {
    invoice: "",
    invoiceNo: "",
    money: 0,
    invoiceDate: "",
    invoiceResult: "",
    invoiceColor: "",
  },
});

const { queryParams, form } = toRefs(data);
/**
 * 初始化数据
 */
function InitDictItem() { }

/**
 * 加载页面table数据
 */
function loadTableData() {
  tableloading.value = true;
  getTHInvoiceListWithPager(queryParams.value).then((res) => {
    tableData.value = res.ResData.Items;
    summary.value = res.ResData.Context;
    queryParams.value.pageTotal = res.ResData.TotalItems;
    tableloading.value = false;
  });
}

function openManual() {
  manualVisible.value = true
}



/**
 * 查询发票
 */
function querySearchAsync(queryString, cb) {

  if (queryString && queryString.length > 4) {
    queryParams.value.Keywords = queryString
    getTHInvoiceList(queryParams.value).then(res => {
      invoiceList.value = res.ResData

      const results = invoiceList.value
        //.filter(invoice => invoice.toLowerCase().includes(queryString.toLowerCase()))
        .map(invoice => ({
          value: invoice
        }));

      setTimeout(() => {
        cb(results);
      }, 10);

    })
  }
}

/**
 * 选择发票
 */
function handleSelectInvoice(item) {
  //console.log(item)
  form.value.invoice = item.value;
  manualVisible.value = false;
  checkInvoice.value = ''
  nextTick(() => {
    inputInvoice.value.focus()
  })
  
}

/**
 * 导出数据
 *  */
function exportData() {
  exportInvoices(queryParams.value).then((res) => {
    window.open(defaultSettings.exportUrl + res.ResData);
  });
}

function formatDate(date) {
  if (!date) return "";
  const options = {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  };
  return new Intl.DateTimeFormat("zh-CN", options).format(new Date(date));
}
/**
 * 点击查询
 */
function handleSearch() {
  queryParams.value.CurrenetPageIndex = 1;
  loadTableData();
}

/** 重置查询操作 */
function resetQuery() {
  proxy.resetForm("searchformRef");
  handleSearch();
}

function getSummaries(param) {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = h("div", { style: { textDecoration: "underline" } }, [
        "合计",
      ]);
      return;
    }

    if (index == 6) {
      sums[index] = summary.value;
      return;
    }
  });

  return sums;
}

/**
 * 当表格的排序条件发生变化的时候会触发该事件
 */
function handleSortChange(column) {
  if (column.prop != null) {
    queryParams.value.Sort = column.prop;
  }
  if (column.order === "ascending") {
    queryParams.value.Order = "asc";
  } else {
    queryParams.value.Order = "desc";
  }
  loadTableData();
}
/**
 * 扫码核验
 */
function openScanInvoice() {
  dialogFormVisible.value = true;
  form.value.invoice = "";
}

function scanInvoice() {
  queryParams.value.Keywords = form.value.invoice;
  scanInvoiceInfo(queryParams.value).then((res) => {
    var result = res.ResData;
    form.value.invoiceNo = result.InvoiceNo ?? "";
    form.value.invoiceDate = result.InvoiceDate ?? "";
    form.value.money = result.Money;
    form.value.invoiceResult = result.invoiceResult;
    form.value.invoiceColor = result.invoiceColor;
    form.value.invoice = "";
    queryParams.value.Keywords = "";
    loadTableData();
  });
}
/**
 * 当用户手动勾选checkbox数据行事件
 */
function handleSelectChange(selection) {
  ids.value = selection.map((item) => item.Id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
loadTableData();
</script>

<style>
.full-width-auto {
  width: 100%;
}
</style>
